const express = require("express")
const router = express.Router()
const multer = require("multer")
const path = require("path")
const {join} = require("path")
const coverDB = require("../../../../db/album")
const fs = require("fs")


// 获取相册
router.get("/getCover",async(req,res)=>{
  try {
    let {type} = req.query
    if(!type){
      let doc = await coverDB.find().populate("author",{Supertube:0,admin:0,pass:0})
      res.send({
        code:0,
        mes:"封面相册数据",
        data:doc
      })
      return
    }
    let doc = await coverDB.find({type}).populate("author",{Supertube:0,admin:0,pass:0})
    res.send({
      code:0,
      mes:"封面相册数据",
      data:doc
    })
  } catch (error) {
    res.send({
      code:5,
      mes:"服务器异常，请稍后再试"
    })
  }
})

// 权限判断 上传
router.use((req,res,next)=>{
  if(!req.session.userInfo.allowPublish){
    return res.send({
      code:15,
      mes:"您没有上传权限，请联系超级管理员进行添加"
    })
  }
  next()
})

// 上传cover文件
let coverUpload = multer({
  storage:multer.diskStorage({
    // 文件存储的目录
    destination(req,file,cb){
      cb(null,join(__dirname,"../../../../static/album/cover/"))
    },
    // 文件的名字
    filename(req,file,cb){
      let name = req.session.userInfo._id
      let ext = path.extname(file.originalname)
      req.coverFile = "static"+name+Date.now()+ext
      cb(null,req.coverFile)  //名字
    }
  })
}).single("file") //name名字 elemetUI默认为file


// 图片上传
router.post("/upload",async(req,res)=>{
  try {
    coverUpload(req,res,async err=>{
      if(err){
        return res.send({
          code:8,
          mes:"md文件上传失败,请刷新后重试"
        })
      }  
      res.send({
        code:0,
        mes:"相册封面图上传成功",
        data:"/album/cover/"+req.coverFile
      }) 
    }) 
  } catch (error) {
    console.log(error)
    res.send({
      code:5,
      mes:"服务器异常，请稍后再试"
    })
  }
})

// 发表相册
router.post("/publish",async(req,res)=>{
  try {
    let {title,src,type} = req.body
    await coverDB.create({
      title,
      src,
      type,
      author:req.session.userInfo._id
    })
    res.send({
      code:0,
      mes:"封面相册发表成功"
    })
  } catch (error) {
    res.send({
      code:5,
      mes:"服务器异常，请稍后再试"
    })
  }
})



module.exports = router